﻿#region Using

using System.Threading;
using WSMon.Engine.Proxy;
using WSMon.Engine.Threading;

#endregion

namespace WSMon.Engine
{
    public static class Core
    {
        public static readonly ThreadPooler ThreadPooler = new ThreadPooler(100);

        public static Configuration Configuration;

        #region Delegates

        public delegate void CheckOutComplatedEventHandler(CheckerProxy checkerProxy, bool returnValue);
        public static event CheckOutComplatedEventHandler CheckOutComplated;

        #endregion

        public static void RunAllChecks()
        {
            foreach (var hosting in Configuration.Hostings)
            {
                RunChecks(hosting);
            }

            ThreadPooler.AllJobsPushed();
        }

        public static void RunChecks(Hosting hosting)
        {
            var checkerList = hosting.GetCheckers();

            for (int index = 0; index < checkerList.Count; index++)
            {
                var checker = checkerList[index];

                var thread = new Thread(RunChecker);
                thread.Start(new CheckerProxy(hosting, checker));

                ThreadPooler.WaitForThreads();
            }
        }

        private static void RunChecker(object objChecker)
        {
            var checkerProxy = (CheckerProxy) objChecker;

            ThreadPooler.Open();

            bool retVal = checkerProxy.Checker.CheckOut();
            CheckOutComplated(checkerProxy, retVal);

            ThreadPooler.Close();
        }
    }
}